package com.redis.seckill.mq.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.redis.seckill.entity.MyOrder;
import com.redis.seckill.entity.Product;
import com.redis.seckill.mq.config.ActiveMQConfig;
import com.redis.seckill.service.MyOrderService;
import com.redis.seckill.service.ProductService;
import com.redis.seckill.utils.RedisUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Service;

import javax.jms.MapMessage;
import java.math.BigDecimal;

/**
 * 消息接收者
 * @date 2020/10/29 9:15
 */
@Log4j2
@Service
public class Receiver {


    @Autowired
    private RedisUtil redisUtil;


    @Autowired
    private MyOrderService myOrderService;

    @Autowired
    private ProductService productService;


    @JmsListener(destination = ActiveMQConfig.QUEUE_NAME)
    public void receive(MapMessage mapMessage){
        try {
//            根据接收的map中的productId得到商品的id
            String productId = mapMessage.getString("productId");
            String userId = mapMessage.getString("userId");
            String quantityStr = mapMessage.getString("quantity");
//            从redis中读取该商品的信息
            String jsonProduct = JSONObject.toJSONString(redisUtil.get("productInfo" + productId));
            Product product = JSONObject.parseObject(jsonProduct, Product.class);

//            判断想要购买的数量是否大于商品剩余的数量
            Integer quantity = Integer.valueOf(quantityStr);
            int num = product.getProductResidue()-quantity;
            if (num < 0){
                log.error("【商品库存不足】");
                throw new RuntimeException("【商品库存不足】");
            }

//            剩下肯定就是数量小于库存了

//            更新redis中商品信息
            product.setProductResidue(product.getProductResidue()-quantity);
            redisUtil.set("productInfo" + productId, JSON.toJSON(product));

//            也可以先写入到redis中，等服务器峰值过去再写入到数据库中。

//           生成订单存到数据库中
            MyOrder myOrder = new MyOrder();
            myOrder.setProductOrder(Integer.valueOf(productId));
            myOrder.setUserOrder(Integer.valueOf(userId));
            myOrder.setProductQuantity(quantity);
            myOrder.setOrderCount(product.getProductPrice().multiply(new BigDecimal(quantity)));
            myOrderService.save(myOrder);

//            更新商品表
            productService.updateById(product);


        }catch (Exception e){
            log.error("【队列接收异常】{}",e.getMessage());
        }
    }
}
